package com.hex.tcpproxy.hx;

/**
 * @author: [wujie]
 * @createTime: [2019/10/10 13:48]
 * @description:
 */
public class DataPacket {
    private String origin;
    private String target;
    private byte[] realData;
    private byte[] allData;

    public DataPacket(String origin, String target, byte[] data) {
        this.origin = origin;
        this.target = target;
        this.realData = data;
        allData = new byte[realData.length + 12];
        writeAddress(allData, 0, origin);
        writeAddress(allData, 6, target);
        System.arraycopy(data, 0, allData, 12, data.length);
    }

    public DataPacket(byte[] allData) {
        this.allData = allData;
        this.origin = readAdress(allData, 0);
        this.target = readAdress(allData, 6);
        int len = allData.length - 12;
        this.realData = new byte[len];
        System.arraycopy(allData, 12, this.realData, 0, len);
    }

    private void writeAddress(byte[] bytes, int start, String address) {
        String[] splits = address.split(":");
        String[] ipStr = splits[0].split("\\.");
        Integer port = Integer.parseInt(splits[1]);
        int high = port >> 8;
        int low = port.shortValue();
        bytes[start] = (byte) Integer.parseInt(ipStr[0]);
        bytes[start + 1] = (byte) Integer.parseInt(ipStr[1]);
        bytes[start + 2] = (byte) Integer.parseInt(ipStr[2]);
        bytes[start + 3] = (byte) Integer.parseInt(ipStr[3]);
        bytes[start + 4] = (byte) high;
        bytes[start + 5] = (byte) low;
    }

    private String readAdress(byte[] bytes, int start) {
        StringBuilder sb = new StringBuilder();
        sb.append(bytes[start + 0] & 0xff).append(".")
                .append(bytes[start + 1] & 0xff).append(".")
                .append(bytes[start + 2] & 0xff).append(".")
                .append(bytes[start + 3] & 0xff).append(":")
                .append((0xff & bytes[start + 4]) * 256 + (0xff & bytes[start + 5]));
        return sb.toString();
    }

    public String getOrigin() {
        return origin;
    }

    public String getTarget() {
        return target;
    }

    public byte[] getRealData() {
        return realData;
    }

    public byte[] getAllData() {
        return allData;
    }

    public static void main(String[] args) {

        byte[] bytes = new byte[6];
        DataPacket dataPacket = new DataPacket(null);
        dataPacket.writeAddress(bytes, 0, "192.168.0.1:23");
        System.out.println(dataPacket.readAdress(bytes, 0));
    }
}
